'use strict';
const {
	mpWxGetSessionKey,
	mpWxGetPhoneNo,
	mpWxGetOpenid
} = require('wx-auth')
const moment = require('moment');
const axios = require('axios');
const {
	assert
} = require('console');
const {
	format
} = require('url');
const db = uniCloud.database();
const dbCmd = db.command;
const userCollection = db.collection('th_user')
exports.main = async (event, context) => {
	const {
		operation,
		data
	} = event;
	switch (operation) {
		case "loginByWeixin": {
			return await loginByWeixin(data);
		}
		
		case "loginnew": {
			return loginnew(data);
		}
		
		case "getuserlist": {
			return await getuserlist();
		}
		
		case "upuserinfo": {
			return await upuserinfo(data);
		}

		case "upweixininfo": {
			return await upweixininfo(data);
		}
		case "upgongde": {
			return await upgongde(data);
		}
		case "getuser": {
			return await getuser();
		}
		case "getmyuser": {
			return await getmyuser(data);
		}
		case "getuserinfo": {
			return await getuserinfo(data);
		}
		default: {
			throw new Error("未找到接口")
		}
	}
};
async function getuser() {
	var ticket = await userCollection.orderBy("num", "desc").get();
	if (ticket.data.length <= 0) {
		return {
			code: 500,
			data: "无数据"
		}
	} else {
		return {
			code: 200,
			data: ticket.data
		}
	}
}
async function getuserinfo(data) {
	var ticket = await userCollection.where({
		openId: data.openId,
	}).get();
	if (ticket.data.length <= 0) {
		return {
			code: 500,
			data: "无数据"
		}
	} else {
		var paiming;
		if(data.type==1)
		{
			paiming = await userCollection.orderBy("num", "desc").get();
		}
		else
		{
			paiming= await userCollection.where(
				dbCmd.or({
					userid: dbCmd.eq(data.openId)
				}, {
					openId: dbCmd.eq(data.openId)
				})
			).orderBy("num", "desc").get();
		}		
		return {
			code: 200,
			data: ticket.data,
			paiming:paiming.data
		}
	}
}
async function getmyuser(data) {
	var ticket = await userCollection.where(
		dbCmd.or({
			userid: dbCmd.eq(data.openId)
		}, {
			openId: dbCmd.eq(data.openId)
		})
	).orderBy("num", "desc").get();
	if (ticket.data.length <= 0) {
		return {
			code: 500,
			data: "无数据"
		}
	} else {
		return {
			code: 200,
			data: ticket.data
		}
	}
}
async function upgongde(data) {

	let res = await userCollection.where({
		openId: data.openId,
	}).update({
		num: dbCmd.inc(data.num),
	})
	if (res.updated > 0) {
		const result = await userCollection.where({
			openId: data.openId
		}).get()
		console.log(result)
		return {
			code: 200,
			data: result.data[0].num
		};
	}
}
async function upweixininfo(data) {

	const result = await userCollection.where({
		openId: data.openId
	}).get()

	if (result.data.length > 0) {
		let user = result.data[0];
		// console.log(2222,data.nickName)
		const now = new Date().getTimezoneOffset() == 0 ? moment().add(8, 'hours').format('YYYY-MM-DD HH:mm:ss') :
			moment().format('YYYY-MM-DD HH:mm:ss');

		const r = await userCollection.doc(user._id).update({
			nickName: data.nickName,
			avatar: data.avatarUrl,
			updateTime: now
		})
		// console.log(22222,r)
		return {
			code: 200,
			data: {
				id: user._id,
				openId: data.openId,
				nickName: data.nickName,
				gender: user.gender,
				avatar: data.avatarUrl,
				city: user.city,
				language: user.language,
				class: user.class
			}
		}
	}
}

async function upuserinfo(data) {
	const result = await userCollection.where({
		openId: data.openId
	}).get()
	// console.log(666,result.data[0].class)
	if (result.data.length > 0) {
		return {
			code: 200,
			data: result.data[0].class
		}
	}
}
async function loginnew(data) {
	// console.log(666, data.data)
	const wxUser = await mpWxGetOpenid(data.code)
	if (wxUser.status == 0) {
		throw new Error(wxUser.msg)
	}
	const result = await userCollection.where({
		openId: wxUser.openid
	}).get()
	let id = null;
	const now = new Date().getTimezoneOffset() == 0 ? moment().add(8, 'hours').format('YYYY-MM-DD HH:mm:ss') :
		moment().format('YYYY-MM-DD HH:mm:ss');

	// 如果已经有了，则更新库里的信息
	if (result.data.length > 0) {
		let user = result.data[0]
		const r = await userCollection.doc(user._id).update({
			// nickName: data.data.userInfo.nickName,
			gender: data.data.userInfo.gender,
			// avatar: data.data.userInfo.avatarUrl,
			city: data.data.userInfo.city,
			language: data.data.userInfo.language,
			updateTime: now
		})
		return {
			code: 200,
			data: {
				id: user._id,
				openId: wxUser.openid,
				nickName: user.nickName,
				gender: data.data.userInfo.gender,
				avatar: user.avatar,
				city: data.data.userInfo.city,
				language: data.data.userInfo.language,
				num: result.data[0].num
				// sessionKey: wxUser.session_key
			}
		};
	} else {
		// 若没有，则插入该用户数据
		const r = await userCollection.add({
			nickName: data.data.userInfo.nickName,
			gender: data.data.userInfo.gender,
			avatar: data.data.userInfo.avatarUrl,
			openId: wxUser.openid,
			num: 0, //等级   初级   中级 高级 
			userid: data.data.userid,
			city: data.data.userInfo.city,
			language: data.data.userInfo.language,
			createTime: now,
			updateTime: now
		})
		if (data.data.userid != "") {
			const result = await userCollection.where({
				openId: data.data.userid
			}).get()
			if (result.data.length > 0) {
				let usernum = result.data[0]
				//更新所有工单为已转账
				let res = await userCollection.where({
					openId: data.data.userid,
				}).update({
					num: usernum.num + 5000,
				})
			}
		}

		return {
			code: 200,
			data: {
				id: r.id,
				nickName: data.data.userInfo.nickName,
				openId: wxUser.openid,
				gender: data.data.userInfo.gender,
				avatar: data.data.userInfo.avatarUrl,
				city: data.data.userInfo.city,
				language: data.data.userInfo.language,
				num: 0
				// sessionKey: wxUser.session_key
			}
		}
	}
}

// 通过微信登录
async function loginByWeixin(data) {
	// 获取openid
	const wxUser = await mpWxGetSessionKey(data)
	if (wxUser.status == 0) {
		throw new Error(wxUser.msg)
	}
	// 通过openid查库里的数据
	const result = await userCollection.where({
		openId: wxUser.userInfo.openId
	}).get()
	let id = null;
	// console.log("result", result.data[0])
	const now = new Date().getTimezoneOffset() == 0 ? moment().add(8, 'hours').format('YYYY-MM-DD HH:mm:ss') :
		moment().format('YYYY-MM-DD HH:mm:ss');

	// 如果已经有了，则更新库里的信息
	if (result.data.length > 0) {
		let user = result.data[0]
		const r = await userCollection.doc(user._id).update({
			// nickName: wxUser.userInfo.nickName,
			gender: wxUser.userInfo.gender,
			// avatar: wxUser.userInfo.avatar,
			city: wxUser.userInfo.city,
			language: wxUser.userInfo.language,
			updateTime: now
		})
		return {
			code: 200,
			data: {
				id: user._id,
				openId: wxUser.userInfo.openId,
				nickName: wxUser.userInfo.nickName,
				gender: wxUser.userInfo.gender,
				avatar: wxUser.userInfo.avatar,
				city: wxUser.userInfo.city,
				language: wxUser.userInfo.language,
				sessionKey: wxUser.session_key
			}
		};
	} else {
		// 若没有，则插入该用户数据
		const r = await userCollection.add({
			nickName: wxUser.userInfo.nickName,
			gender: wxUser.userInfo.gender,
			avatar: wxUser.userInfo.avatar,
			openId: wxUser.userInfo.openId,
			avatar: wxUser.userInfo.avatar,
			city: wxUser.userInfo.city,
			language: wxUser.userInfo.language,
			createTime: now,
			updateTime: now,
			num: '' //等级   初级   中级 高级 
		})
		return {
			code: 200,
			data: {
				id: r.id,
				nickName: wxUser.userInfo.nickName,
				openId: wxUser.userInfo.openId,
				gender: wxUser.userInfo.gender,
				avatar: wxUser.userInfo.avatar,
				city: wxUser.userInfo.city,
				language: wxUser.userInfo.language,
				sessionKey: wxUser.session_key
			}
		}
	}
}

